package cn.livingCloud.controller.user;

import cn.livingCloud.dto.ImageListDto;
import cn.livingCloud.dto.ImageUploadConfigDto;
import cn.livingCloud.dto.ImageUploadDto;
import cn.livingCloud.service.ImageUploadService;
import cn.livingCloud.utils.BindingResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * Created by 唐旭 on 2016/1/27.
 */
@Controller
@RequestMapping("/admin/image")
public class ImageResourceController {
    @Autowired
    @Qualifier("imageUploadServiceImpl")
    private ImageUploadService uploadService;

    @RequestMapping(value = "/upload", params = "action=config")
    @ResponseBody
    public ImageUploadConfigDto getConfig() {
        return uploadService.loadImageUploadConfigDto();
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST, params = "action=uploadimage")
    @ResponseBody
    public ImageUploadDto uploadImage(@ModelAttribute("uploadDto") @Valid ImageUploadDto imageFile, BindingResult result) {
        if (result.hasErrors()) {
            return BindingResultUtils.buildErrorMessage(result, imageFile);
        }
        return uploadService.saveUploadImage(imageFile);
    }

    @RequestMapping(value = "/upload", params = "action=listImage")
    @ResponseBody
    public ImageListDto listImage(ImageListDto listDto, Model model) {
        uploadService.loadImageListDto(listDto);
        return listDto;
    }

//    @RequestMapping(value = "/upload", params = "action=listImage")
//    @ResponseBody
//    public String listImage(ImageListDto listDto, Model model) {
//       return "{\"state\":\"SUCCESS\",\"list\":\n" +
//               "[{\"url\":\"\\/server\\/ueditor\\/upload\\/image\\/3.jpg\"}]\n" +
//               ",\"start\":\"0\",\"total\":29}";
//    }
}
